<?php
/*
 * +--------------------------------------------------------------------
 * 作 者: hemm <1429655840@qq.com>
 * +----------------------------------------------------------------------
 * 创建日期：2015-07-08
 * +----------------------------------------------------------------------
 * 文件描述：用户管理
 * +----------------------------------------------------------------------
 * 升级记录：songyb整理优化功能（2015-07-08）
 * weilp整理用户导入及用户主键生成
 * +----------------------------------------------------------------------
 */
header("Content-Type:text/html;Charset=utf-8");

class SchoolAction extends CommonAction
{

    /**
     * 系统用户管理
     */
    public function index()
    {
        $model = new SchoolModel();
        // 条件检索
        if (! empty($_REQUEST['search_keyword'])) {
            $where['code|name|area_code'] = array(
                'like',
                '%' . $_REQUEST['search_keyword'] . '%'
            );
        }
        
        // 通过省市县检索
        if (! empty($_REQUEST['area_code'])) {
            $where['area_code'] = $_REQUEST['area_code'];
        } elseif (empty($_REQUEST['area_code']) && ! empty($_REQUEST['city_code'])) {
            $where['area_code'] = array(
                'like',
                $_REQUEST['city_code'] . '%'
            );
        } elseif (empty($_REQUEST['area_code']) && empty($_REQUEST['city_code']) && ! empty($_REQUEST['province_code'])) {
            $where['area_code'] = array(
                'like',
                $_REQUEST['province_code'] . '%'
            );
        }
        
        // 分页处理
        import('ORG.Util.Page'); // 导入分页类
        $count = $model->where($where)->count(); // 查询满足要求的总记录数
        
        $p = $this->_page($model, 'id'); // 分页所需信息
        $page = new Page($count, $p['listRows']); // 实例化分页类 传入总记录数和每页显示的记录数
        
        $data = $model->field("id,
 		                       code,
 		                       name,
 		                       area_code,
 		                       get_user_name(operator) operator,
    						   update_date")
            ->where($where)
            ->order("`" . $p['order'] . "` " . $p['sort'])
            ->limit($page->firstRow . ', ' . $page->listRows)
            ->select();
        $this->assign('data', $data);
        $show = $page->show(); // 分页显示输出
        $this->assign('show', $show); // 绑定分页显示字符串
        
        $this->assign('province_list', get_province_list()); // 省份列表
                                                             // 查询该省份下的市州列表
        if (! empty($_REQUEST['province_code'])) {
            $model = new CityModel();
            $city_list = $model->field("code, name")
                ->where("province_code = '" . $_REQUEST['province_code'] . "'")
                ->select();
            $this->assign('city_list', $city_list);
        }
        
        // 查询该市州下的县区列表
        if (! empty($_REQUEST['city_code'])) {
            $model = new AreaModel();
            $area_list = $model->field("code, name")
                ->where("city_code = '" . $_REQUEST['city_code'] . "'")
                ->select();
            $this->assign('area_list', $area_list);
        }
        
        $this->display();
    }

    /**
     * 添加用户
     */
    public function add()
    {
        $this->assign('province_list', get_province_list()); // 省份列表
        $this->display();
    }

    /**
     * 将用户信息添加至数据库
     */
    public function insert()
    {
        $data = $this->add_user($this->_request(), $msg);
        if (false !== $data) {
            $this->success($msg, __APP__ . '?g=Admin&m=School&a=index');
        } else {
            $this->error($msg);
        }
    }

    /**
     * 修改用户信息页面显示
     */
    public function edit()
    {
        // 查询当前用户信息
        $model = new SchoolModel();
        $data = $model->where("id = '" . $_REQUEST['id'] . "'")->find();
        if (empty($data)) {
            $this->error('未找到您要修改的用户信息！');
        }
        $this->assign('data', $data);
        
        // 获取当前用户的省份编码
        $province_code = substr($data['area_code'], 0, 2);
        $this->assign('province_code', $province_code);
        // 获取当前用户的市州编码
        $city_code = substr($data['area_code'], 0, 4);
        $this->assign('city_code', $city_code);
        
        // 省市县联动信息绑定
        $this->assign('province_list', get_province_list()); // 省份列表
        $this->assign('city_list', get_city_list($province_code)); // 市州列表
        $this->assign('area_list', get_area_list($city_code)); // 县区列表
                                                               
        // 数据字典信息绑定
        $this->assign('gender_list', set_field_dict_list('user', 'gender'));
        $this->assign('nation_list', set_field_dict_list('user', 'nation'));
        $this->assign('status_list', set_field_dict_list('user', 'status'));
        $this->display();
    }

    /**
     * 更新用户信息至数据库
     */
    public function update()
    {
        $data = $this->update_user($this->_request(), $msg);
        if (false !== $data) {
            redirect(__APP__ . '?g=Admin&m=School&a=index');
        } else {
            $this->error($msg);
        }
    }

    /**
     * 删除用户信息
     */
    public function delete()
    {
        $userIds = $this->_request('ids');
        if (false !== $this->delete_user($userIds, $msg)) {
            redirect($_SERVER['HTTP_REFERER']);
        } else {
            $this->error($msg);
        }
    }

    /**
     * 添加用户【供其他模块调用】
     */
    public function add_user($post_data, &$msg)
    {
        $model = new SchoolModel();
        if (! empty($post_data['pwd'])) {
            $post_data['pwd'] = md5($post_data['pwd']);
        }
        if (false !== $model->create($post_data, 1)) {
            $insertId = $model->add();
            if (false !== $insertId) {
                $msg = '用户添加成功！';
                return $insertId;
            } else {
                $msg = '用户添加失败！';
                return false;
            }
        } else {
            $msg = '用户添加失败！' . $model->getError();
            return false;
        }
    }

    /**
     * 更新用户【供其他模块调用】
     * 
     * @param unknown $post_data            
     * @param unknown $msg            
     */
    public function update_user($post_data, &$msg)
    {
        $model = new SchoolModel();
        // 对密码字段作特殊处理
        if (! empty($post_data['pwd'])) {
            $post_data['pwd'] = md5($post_data['pwd']);
        } else {
            unset($post_data['pwd']);
        }
        if (false !== $model->create($post_data, 0)) {
            if (false !== $model->save()) {
                $msg = '用户修改成功！';
                return true;
            } else {
                $msg = '用户修改失败！';
                return false;
            }
        } else {
            $msg = '用户修改失败！' . $model->getError();
            return false;
        }
    }

    /**
     * 删除用户【供其他模块调用】
     * 
     * @param array $userIds            
     * @param
     *            string &$msg
     * @return boolean
     */
    public function delete_user($userIds, &$msg)
    {
        if (! empty($userIds) && is_array($userIds)) {
            $model = new SchoolModel();
            $model->startTrans();
            $id = implode("','", $userIds); // 用','分割id数组，以便于拼装sql语句
            $id = "'" . $id . "'"; // 拼装sql语句，结果为'firstId','secondId',…
            if (false !== $model->where("id in(" . $id . ")")->delete()) {
                $msg = '用户删除成功！';
                $model->commit();
                return true;
            } else {
                $msg = '用户删除失败！';
                $model->rollback();
                return false;
            }
        } else {
            $msg = '您未选中任何记录！';
            return false;
        }
    }

    /**
     * 通过Validform框架实时验证【用户名】的唯一性
     * ajaxurl指定的文件可以接收到Post过来的两个值，分别是param和name，param是该元素的值，name是该元素的name名称。可以通过区别name来把一个表单下，多个实时验证请求，都指定到同一个文件。
     */
    public function check_username()
    {
        if (! empty($_REQUEST['userid'])) {
            $where['_string'] = "id <> '" . $_REQUEST['userid'] . "'"; // 此条件用于修改用户信息时用户名查重检测（查重时忽略本身的用户名）
        }
        $where['name'] = $_REQUEST['param'];
        
        $model = new SchoolModel();
        $userid = $model->where($where)->getField('id');
        // 若数据库中该用户名不存在，则该用户名可以使用
        if (empty($userid)) {
            echo 'y'; // Validform实时验证成功时只能输出'y'，其它任何字符将作为验证失败提示信息返回
        } else {
            echo '该用户名已经存在，请选择其他！';
        }
    }

    /*
     * 导入界面
     *
     */
    public function import()
    {
        $head_array = C('PLDR_SCHOOL_EXCEL_HEAD');
        $this->assign('head_string', implode(',', $head_array));
        $this->assign('province_list', get_province_list()); // 省份列表
        $this->display();
    }
    
    // 用户导入（操作）
    public function importDo()
    {
        $area_code = $_REQUEST['area_code'];
        $model = new SchoolModel();
        import("ORG.Net.UploadFile");
        // $webid = $this->get_webid();
        if (! empty($_FILES['xls']['name'])) {
            $upload = new UploadFile(); // 实例化上传类
            $upload->maxSize = - 1; // 设置附件上传大小，-1无限制大小
            $upload->savePath = C('PLDR_UPLOAD_PATH') . $model->getWebId() . C('PLDR_AFFIX_PATH');
            $upload->allowExts = C('PLDR_XLS_ALLOWEXTS');
            $upload->saveRule = uniqid; // 设置上传文件的保存规则
            
            if (! ($info = $upload->uploadOne($_FILES['xls'], $upload->savePath))) { // 上传错误 提示错误信息
                $this->error('操作失败：文件上传错误！' . $upload->getErrorMsg());
            } else {
                $memory_limit = ini_get("memory_limit");
                ini_set("memory_limit ", C('MEMORY_LIMIT'));
                $file = $info[0]['savepath'] . $info[0]['savename'];
                $xls_data = $this->importExecl($file);
                $data = $xls_data['data'][0]['Content'];
                
                // 检测头部是否符合要求
                $count = $xls_data['data'][0]['Cols'];
                
                $head_array = C('PLDR_SCHOOL_EXCEL_HEAD');
                if ($count != count($head_array)) {
                    $this->error("表中列的个数为" . $count . "列,与要求的" . count($head_array) . "列不符，请核对后再导入,请务必保证在表格中不要使用公式和函数！");
                }
                $head_xls = $data[1];
                foreach ($head_array as $key => $row) {
                    if ($row != str_replace(' ', '', $head_xls[$key])) {
                        $this->error("表中列名“" . $head_xls[$key] . "”与要求的“" . $row . "”不一致，请核对后再导入,请务必保证在表格中不要使用公式和函数！");
                    }
                }
                
                array_shift($data); // 去掉头部
                                    
                // 修改键值
                $head_xls = array_flip($head_xls);
                array_unshift($data, $head_xls);
                array_shift($data);
                $new_no = 0;
                $exits_no = 0;
                // $area_code = '';
                
                // 开启事务
                $model->startTrans();
                foreach ($data as $key => $row) {
                    if (empty($temp_data)) {
                        // $sql_data['id'] = $row[0];
                        // $sql_data['groupsid'] = $row[1];
                        $sql_data['code'] = $row[0];
                        // $sql_data['pwd'] = md5(substr($row[3], -6));
                        $sql_data['name'] = $row[1];
                        $sql_data['area_code'] = $area_code;
                        $sql_data['operator'] = $model->getuserId();
                        $sql_data['update_date'] = $model->getShortDate();
                        if (false === $model->add($sql_data)) {
                            $model->rollback();
                            $this->error('导入失败1：' . $model->getDbError());
                        }
                        unset($sql_data);
                    }
                }
                // 提交事务
                $model->commit();
                ini_set("memory_limit", $memory_limit);
                $this->success("导入成功，此次导入" . ($xls_data['data'][0]['Rows'] - 1) . "条记录。", __APP__ . '?g=Admin&m=School&a=index');
            }
        }
    }

    /**
     * 导入数据
     */
    public function importExecl($file)
    {
        if (! file_exists($file)) {
            return array(
                "error" => 0,
                'message' => 'file not found!'
            );
        }
        Vendor("PHPExcel.IOFactory");
        $objReader = PHPExcel_IOFactory::createReader('Excel5');
        try {
            $PHPReader = $objReader->load($file);
        } catch (Exception $e) {}
        if (! isset($PHPReader))
            return array(
                "error" => 0,
                'message' => 'read error!'
            );
        $allWorksheets = $PHPReader->getAllSheets();
        $i = 0;
        foreach ($allWorksheets as $objWorksheet) {
            $sheetname = $objWorksheet->getTitle();
            
            $allRow = $objWorksheet->getHighestRow(); // how many rows
            
            $highestColumn = $objWorksheet->getHighestColumn(); // how many columns
            
            $allColumn = PHPExcel_Cell::columnIndexFromString($highestColumn);
            
            $array[$i]["Title"] = $sheetname;
            $array[$i]["Cols"] = $allColumn;
            $array[$i]["Rows"] = $allRow;
            $arr = array();
            $isMergeCell = array();
            foreach ($objWorksheet->getMergeCells() as $cells) { // merge cells
                foreach (PHPExcel_Cell::extractAllCellReferencesInRange($cells) as $cellReference) {
                    $isMergeCell[$cellReference] = true;
                }
            }
            for ($currentRow = 1; $currentRow <= $allRow; $currentRow ++) {
                $row = array();
                for ($currentColumn = 0; $currentColumn < $allColumn; $currentColumn ++) {
                    ;
                    $cell = $objWorksheet->getCellByColumnAndRow($currentColumn, $currentRow);
                    $afCol = PHPExcel_Cell::stringFromColumnIndex($currentColumn + 1);
                    $bfCol = PHPExcel_Cell::stringFromColumnIndex($currentColumn - 1);
                    $col = PHPExcel_Cell::stringFromColumnIndex($currentColumn);
                    // echo $cell;
                    $address = $col . $currentRow;
                    $value = $objWorksheet->getCell($address)->getValue();
                    if (substr($value, 0, 1) == '=') {
                        return array(
                            "error" => 0,
                            'message' => 'can not use the formula!'
                        );
                        exit();
                    }
                    if ($isMergeCell[$col . $currentRow] && $isMergeCell[$afCol . $currentRow] && ! empty($value)) {
                        $temp = $value;
                    } elseif ($isMergeCell[$col . $currentRow] && $isMergeCell[$col . ($currentRow - 1)] && empty($value)) {
                        $value = $arr[$currentRow - 1][$currentColumn];
                    } elseif ($isMergeCell[$col . $currentRow] && $isMergeCell[$bfCol . $currentRow] && empty($value)) {
                        $value = $temp;
                    }
                    $row[$currentColumn] = $value;
                }
                $arr[$currentRow] = $row;
            }
            $array[$i]["Content"] = $arr;
            
            $i ++;
        }
        spl_autoload_register(array(
            'Think',
            'autoload'
        )); // must, resolve ThinkPHP and PHPExcel conflicts
        unset($objWorksheet);
        unset($PHPReader);
        unset($PHPExcel);
        unlink($file);
        return array(
            "error" => 1,
            "data" => $array
        );
    }

    /*
     * 生成主键字段
     */
    public function generate_primarykey($schoolkey_left, &$schoolkey_right)
    {
        if (! empty($schoolkey_right)) {
            $schoolkey_right = (int) $schoolkey_right['id'] + 1;
            switch (strlen($schoolkey_right)) {
                case 1:
                    return $schoolkey_left . '00000' . $schoolkey_right;
                case 2:
                    return $schoolkey_left . '0000' . $schoolkey_right;
                case 3:
                    return $schoolkey_left . '000' . $schoolkey_right;
                case 4:
                    return $schoolkey_left . '00' . $schoolkey_right;
                case 5:
                    return $schoolkey_left . '0' . $schoolkey_right;
                case 1:
                    return $schoolkey_left . $schoolkey_right;
            }
        } else {
            return $schoolkey_left . '000001';
        }
    }
}

?>